#include "cabinet_return_dialog.h"
#include <QTimer>
#include <QApplication>
#include <QMessageBox>
#include <QStackedWidget>

CabinetReturnDialog::CabinetReturnDialog(QWidget *parent)
    : QDialog(parent), phoneEdit(nullptr), pwdEdit(nullptr),
      backBtn(nullptr), okBtn(nullptr), keyboard(nullptr), phonePasswordWidget(nullptr), tipWidget(nullptr)
{
    setWindowTitle("离场退柜");
    setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);
    setWindowState(Qt::WindowFullScreen);
    this->showFullScreen();

    setupUI();
    setupConnections();
}

CabinetReturnDialog::~CabinetReturnDialog()
{
    // KeyboardManager::getInstance().releaseNumberKeyboard();
}

void CabinetReturnDialog::setupUI()
{
    mainLayout = new QVBoxLayout(this);
    mainLayout->setSpacing(24);
    mainLayout->setContentsMargins(32, 32, 32, 32);

    // 顶部按钮区
    QWidget *topBtnWidget = new QWidget(this);
    QHBoxLayout *topBtnLayout = new QHBoxLayout(topBtnWidget);
    topBtnLayout->setSpacing(40);
    topBtnLayout->setContentsMargins(0, 0, 0, 0);

    phonePwdBtn = new QPushButton("电话密码退柜", topBtnWidget);
    braceletPalmBtn = new QPushButton("手环/掌静脉退柜", topBtnWidget);

    QString btnStyle = "QPushButton {"
                       "font-size: 32px;"
                       "font-weight: bold;"
                       "background-color: #01ddfd;"
                       "color: white;"
                       "border-radius: 16px;"
                       "padding: 32px 0px;"
                       "margin: 0px;"
                       "min-height: 80px;"
                       "}"
                       "QPushButton:hover {"
                       "background-color: #0099cc;"
                       "}";

    phonePwdBtn->setStyleSheet(btnStyle);
    braceletPalmBtn->setStyleSheet(btnStyle);

    phonePwdBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    braceletPalmBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    topBtnLayout->addWidget(phonePwdBtn);
    topBtnLayout->addWidget(braceletPalmBtn);

    mainLayout->addWidget(topBtnWidget);

    // 下方内容用 QStackedWidget
    stackedWidget = new QStackedWidget(this);

    setupPhonePasswordWidget();
    setupTipWidget();

    stackedWidget->addWidget(phonePasswordWidget); // index 0
    stackedWidget->addWidget(tipWidget);           // index 1
    mainLayout->addWidget(stackedWidget);

    stackedWidget->setCurrentIndex(0);
}

void CabinetReturnDialog::setupPhonePasswordWidget()
{
    phonePasswordWidget = new QWidget(this);
    QHBoxLayout *phonePwdMainLayout = new QHBoxLayout(phonePasswordWidget);

    // 左侧输入区
    QWidget *inputWidget = new QWidget(phonePasswordWidget);
    QVBoxLayout *inputLayout = new QVBoxLayout(inputWidget);

    // 电话号码
    QLabel *phoneLabel = new QLabel("电话号码：", inputWidget);
    phoneLabel->setStyleSheet("font-size: 56px; font-weight: bold;");
    phoneEdit = new QLineEdit(inputWidget);
    phoneEdit->setPlaceholderText("请输入电话号码");
    phoneEdit->setFocusPolicy(Qt::StrongFocus);
    phoneEdit->setMinimumHeight(96);
    phoneEdit->setStyleSheet("font-size: 56px;");

    // 密码
    QLabel *pwdLabel = new QLabel("密码：", inputWidget);
    pwdLabel->setStyleSheet("font-size: 56px; font-weight: bold;");
    pwdEdit = new QLineEdit(inputWidget);
    pwdEdit->setPlaceholderText("请输入密码");
    pwdEdit->setEchoMode(QLineEdit::Password);
    pwdEdit->setFocusPolicy(Qt::StrongFocus);
    pwdEdit->setMinimumHeight(96);
    pwdEdit->setStyleSheet("font-size: 56px;");

    inputLayout->addWidget(phoneLabel);
    inputLayout->addWidget(phoneEdit);
    inputLayout->addWidget(pwdLabel);
    inputLayout->addWidget(pwdEdit);

    // 底部按钮
    QHBoxLayout *bottomBtnLayout = new QHBoxLayout();
    backBtn = new QPushButton("返回", inputWidget);
    okBtn = new QPushButton("确认", inputWidget);
    backBtn->setStyleSheet("font-size: 24px; padding: 12px 48px;");
    okBtn->setStyleSheet("font-size: 24px; padding: 12px 48px;");
    backBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    okBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    bottomBtnLayout->addWidget(backBtn);
    bottomBtnLayout->addSpacing(40);
    bottomBtnLayout->addWidget(okBtn);
    inputLayout->addLayout(bottomBtnLayout);

    inputWidget->setLayout(inputLayout);

    // 右侧数字键盘
    keyboard = KeyboardManager::getInstance().getNumberKeyboard(phonePasswordWidget);
    keyboard->setMinimumWidth(400);
    keyboard->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    phonePwdMainLayout->addWidget(inputWidget, 2);
    phonePwdMainLayout->addWidget(keyboard, 3);

    phonePasswordWidget->setLayout(phonePwdMainLayout);
}

void CabinetReturnDialog::setupTipWidget()
{
    tipWidget = new QWidget(this);
    QVBoxLayout *tipLayout = new QVBoxLayout(tipWidget);
    QLabel *tipLabel = new QLabel("点击手环/掌静脉退柜按钮", tipWidget);
    tipLabel->setAlignment(Qt::AlignCenter);
    tipLabel->setStyleSheet("font-size: 32px; color: #0099cc; margin-top: 120px;");
    tipLayout->addWidget(tipLabel);
    tipWidget->setLayout(tipLayout);
}

void CabinetReturnDialog::setupConnections()
{
    connect(phonePwdBtn, &QPushButton::clicked, this, [=]()
            { stackedWidget->setCurrentIndex(0); });
    connect(braceletPalmBtn, &QPushButton::clicked, this, [=]()
            { stackedWidget->setCurrentIndex(1); });
    connect(backBtn, &QPushButton::clicked, this, &QDialog::reject);

    connect(okBtn, &QPushButton::clicked, this, &CabinetReturnDialog::onOkBtnClicked);

    connect(keyboard, &Keyboard::keyPressed, [=](int key, QString value)
            {
        QWidget *focusWidget = QApplication::focusWidget();
        if (focusWidget && qobject_cast<QLineEdit*>(focusWidget)) {
            QLineEdit *lineEdit = qobject_cast<QLineEdit*>(focusWidget);
            if (key == Qt::Key_Backspace) {
                lineEdit->backspace();
            } else if (key == Qt::Key_Enter || key == Qt::Key_Return) {
                if (lineEdit == phoneEdit)
                    pwdEdit->setFocus();
                else if (lineEdit == pwdEdit)
                    okBtn->click();
            } else {
                lineEdit->insert(value);
            }
        } });
}

void CabinetReturnDialog::onOkBtnClicked()
{
    QString phone = phoneEdit->text();
    QString pwd = pwdEdit->text();

    if (phone.isEmpty() || pwd.isEmpty())
    {
        QMessageBox::warning(this, "输入错误", "请输入电话号码和密码!");
        return;
    }

    // 获取设备配置（可根据实际情况调整为从文件或参数获取）
    DeviceConfig config = BoardUtils::getInstance().loadDeviceConfig("device_config.txt");

    // 验证密码
    PersonConfig person_config = BoardUtils::getInstance().httpGetPersonConfig(
        config.brand_code,
        config.organization,
        config.zone,
        phone.toStdString());
    std::string serverPassword = person_config.passwd;
    if (serverPassword.empty() || pwd.toStdString() != serverPassword)
    {
        QMessageBox::warning(this, "验证失败", "会员信息或密码错误!");
        return;
    }

    // 查询柜子
    Lock lock = BoardUtils::getInstance().httpQueryLock(
        config.brand_code,
        config.organization,
        config.zone,
        phone.toStdString(),
        "流动柜");
    if (lock.controller_id.empty() || lock.lock_numble.empty())
    {
        QMessageBox::warning(this, "查询失败", "未找到您分配的柜子，请确认是否已存包!");
        return;
    }

    // 退柜
    Lock returnLock = BoardUtils::getInstance().httpReturnLock(
        config.brand_code,
        config.organization,
        config.zone,
        phone.toStdString(),
        "流动柜");
    if (returnLock.status != "未使用")
    {
        QMessageBox::warning(this, "退柜失败", "退柜失败，请联系工作人员!");
        return;
    }

    // 开锁
    int controller_id = 0, lock_number = 0, cabinet_number = 0;
    try
    {
        controller_id = std::stoi(lock.controller_id);
        lock_number = std::stoi(lock.lock_numble);
        cabinet_number = std::stoi(lock.cabinet_number);
    }
    catch (const std::exception &e)
    {
        QMessageBox::warning(this, "数据错误", "柜子信息格式错误，请联系工作人员!");
        return;
    }
    bool openResult = BoardUtils::getInstance().serial()->openLock(controller_id, lock_number);
    if (openResult)
    {
        QMessageBox::information(this, "退柜成功", QString("已为您打开 %1 号柜子，请取出物品并关闭柜门").arg(cabinet_number));
        BoardUtils::getInstance().httpUploadLog(
            config.brand_code,
            config.organization,
            config.zone,
            phone.toStdString(),
            std::to_string(cabinet_number),
            "流动柜",
            "离场退柜");
        accept();
    }
    else
    {
        QMessageBox::warning(this, "开锁失败", "柜子已退还，但开锁失败，请联系工作人员");
    }
}

void CabinetReturnDialog::showEvent(QShowEvent *event)
{
    QDialog::showEvent(event);
    if (keyboard && !keyboard->isVisible())
    {
        keyboard->show();
    }
    QTimer::singleShot(100, [this]()
                       { phoneEdit->setFocus(); });
}

void CabinetReturnDialog::closeEvent(QCloseEvent *event)
{
    KeyboardManager::getInstance().releaseNumberKeyboard();
    QDialog::closeEvent(event);
}